<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                              |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: xiangminghu@clcw.com.cn                                        |
// +------------------------------------------------------------------------+
//

namespace AuctionCore\AuctionOrder;

use AuctionCore\Account\Back\Employee;
use AuctionCore\CarResource\CarModel;
use AuctionCore\Other\Address;
use AuctionCore\System\AuctionException;

/**
 * 双方磋商
 * Class Consult
 *
 * @author Xmh
 */
class Consult
{
    private $Consult;
    private $ConsultTraceLog;
    private $CarModel;
    private $Addr;

    public function __construct()
    {
        $this->Consult = M('Consult');
        $this->ConsultTraceLog = M('ConsultTraceLog');
        $this->CarModel = new CarModel();
        $this->Addr = new Address();
    }

    /**
     * 添加磋商记录
     *
     * @param $order_id
     * @param $car_id
     * @param $owner_id
     * @param $dealer_id
     *
     * @return bool|mixed
     */
    public static function add_consult($order_id, $car_id, $owner_id, $dealer_id)
    {
        if ($order_id < 1 || $car_id < 1 || $owner_id < 1 || $dealer_id < 1) return false;
        $data = [
            'order_id' => intval($order_id),
            'car_id' => intval($car_id),
            'owner_id' => intval($owner_id),
            'dealer_id' => intval($dealer_id),
            'consult_status' => 1,
            'createtime' => date("Y-m-d H:i:s")
        ];

        return M('consult')->add($data);
    }

    /**
     * 获取双方磋商的列表
     *
     * @param integer $page
     * @param int     $size
     * @param array   $params
     *
     * @return multitype:unknown string
     */
    public function get_consult_list($page = 1, $size = 10, $params)
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $size = (int)$size < 1 ? 10 : (int)$size;
        $map = array();
        if ($params['status'] > 1) {
            if (!$params['auth']) {
                $map['con.emp_id'] = array('eq', $params['emp_id']);  //分配给自己跟踪的拍单
            } else {
                $map['con.emp_id'] = array('gt', 0);
            }
        } else {
            $map['con.emp_id'] = array('eq', '0'); //尚未分配客服跟踪的拍单
        }
        if ($params['status']) {
            $map['con.consult_status'] = ['eq', $params['status']];
        }
        if ($params['trace_start_time']) {
            $map['con.next_trace_time'] = array('egt', $params['trace_start_time'] . ' 00:00:00');
        }
        if ($params['trace_end_time']) {
            $map['con.next_trace_time'] = array('elt', $params['trace_end_time'] . ' 23:59:59');
        }
        if ($params['trace_start_time'] && $params['trace_end_time']) {
            $map['con.next_trace_time'] = array(array('egt', $params['trace_start_time'] . ' 00:00:00'), array('elt', $params['trace_end_time'] . ' 23:59:59'));
        }
        if ($params['consult_start_time']) {
            $map['con.updatetime'] = array('egt', $params['consult_start_time'] . ' 00:00:00');
        }
        if ($params['consult_end_time']) {
            $map['con.updatetime'] = array('elt', $params['consult_end_time'] . ' 23:59:59');
        }
        if ($params['consult_start_time'] && $params['consult_end_time']) {
            $map['con.updatetime'] = array(array('egt', $params['consult_start_time'] . ' 00:00:00'), array('elt', $params['consult_end_time'] . ' 23:59:59'));
        }
        if ($params['comefrom']) {
            $map['co.comefrom'] = ['eq', $params['comefrom']];
        }
        if (!empty($params['location_area'])) {
            $map['c.location_area'] = ['eq', $params['location_area']];
        }
        if (!empty($params['order_no'])) {
            $order_no = trim($params['order_no']);
            $map['o.order_no'] = ['LIKE', '%' . $order_no . '%'];
        }
        if (empty($params['location_area']) && $params['bc_city']) {
            $map['c.location_area'] = ['in', $params['bc_city']];
        }
        //要查询的列表
        $cols = "o.order_id,o.order_no,o.status,o.fail_type,o.last_time,o.bid_best_price,o.bidding_best_price,o.reserve_price,o.success_price,
                 o.company_subsidies,c.car_id,c.car_no,c.plate_suffix,c.plate_prefix,c.location_area,c.brand_id,c.series_id,c.model_id,c.car_status,c.car_source,
                 co.owner_id,co.seller_name,co.phone,co.next_trace_time,co.sign_reserve_time,co.comefrom,
                 con.id,con.emp_id,con.consult_status,con.next_trace_time,con.updatetime,con.createtime";
        $prefix = C('DB_PREFIX');
        $order = 'con.updatetime DESC';
        $total = $this->Consult->alias('con')
            ->join($prefix . "order as o ON o.order_id = con.order_id")
            ->join($prefix . "cars as c ON c.car_id = con.car_id")
            ->join($prefix . "car_owner as co ON co.owner_id = con.owner_id")
//            ->join($prefix . "car_dealer as cd ON cd.dealer_id = con.dealer_id")
            ->where($map)->count();
        $list = $this->Consult->alias('con')->field($cols)
            ->join($prefix . "order as o ON o.order_id = con.order_id")
            ->join($prefix . "cars as c ON c.car_id = con.car_id")
            ->join($prefix . "car_owner as co ON co.owner_id = con.owner_id")
//            ->join($prefix . "car_dealer as cd ON cd.dealer_id = con.dealer_id")
            ->where($map)->limit($size)->page($page)->order($order)->select();
//        echo M()->_sql();
        $show_from = \AuctionCore\Other\Channel::get_from();  //获取渠道来源信息
        if (!empty($list)) {
            foreach ($list as $key => $val) {
                $list[$key]['order_no'] = $val['order_no'];
                $list[$key]['location_area_name'] = $this->Addr->get_name_by_code($val['location_area']);
                $brand = $this->CarModel->get_model_by_id($val['brand_id'], 'brand');
                $series = $this->CarModel->get_model_by_id($val['series_id'], 'series');
                $model = $this->CarModel->get_model_by_id($val['model_id']);
                $list[$key]['car_no'] = $val['car_no'];
                $list[$key]['model'] = $brand['name'] . ' ' . $series['name']   . ' ' . $model['name'];
                $bidding_best_price = $val['bidding_best_price'] > $val['bid_best_price'] ? $val['bidding_best_price'] : $val['bid_best_price'];
                $list[$key]['bidding_best_price'] = format_money($bidding_best_price);
                $list[$key]['reserve_price'] = format_money($val['reserve_price']);
                //磋商成交价
                $list[$key]['consult_price'] = format_money($val['success_price'] + $val['company_subsidies']);
                $list[$key]['next_trace_time'] = $val['next_trace_time'] > 0 ? transform_date($val['next_trace_time']) : '--';
                $list[$key]['createtime'] = date("Y-m-d H:i", strtotime($val['createtime']));
                $list[$key]['sign_reserve_time'] = transform_date($val['sign_reserve_time']);
                $list[$key]['consult_time'] = $val['updatetime'];
                $list[$key]['phone_has_star'] = showHideMobile($val['phone']);
                //渠道来源
                if (!empty($val['comefrom'])) {
                    if (empty($val['comefrom_url'])) {
                        $channel_from = $show_from[$val['comefrom']];
                    } else {
                        $channel_from = "<a href='" . $val['comefrom_url'] . "' target='blank' rel='noreferrer'>" . $show_from[$val['comefrom']] . "</a>";
                    }
                } else {
                    $channel_from = '未知';
                }
                $list[$key]['channel_from'] = $channel_from;
                if ($params['auth']) {
                    $consult_server = Employee::user_info_id($val['emp_id']);
                    $list[$key]['consult_service'] = $consult_server['real_name'];
                }
            }
        }
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;
    }

    /**
     * 获取双方磋商的列表
     *
     * @param integer $page
     * @param int     $size
     * @param array   $params
     *
     * @return multitype:unknown string
     */
    public function consult_detail($consult_id)
    {
        $condition['con.id'] = ['eq', $consult_id];
        //要查询的列表
        $cols = "o.order_id,o.order_no,o.status,o.last_time,o.transfer_fee,o.bid_best_price,o.bidding_best_price,o.scene_id,
                 o.success_price,o.reserve_price,o.bidding_end_time,o.company_subsidies,o.consult_increase,o.commision,
                 c.car_id,c.car_no,c.plate_suffix,c.plate_prefix,c.location_area,c.brand_id,c.series_id,c.model_id,c.car_source,
                 c.car_color,c.emission,c.pointer_mileage,c.reg_city,c.first_reg_date,c.composite_state,c.history_state,
                 c.accident_level,c.transfer_limit,c.vin,c.suggest_min_price,c.suggest_max_price,c.au_times,
                 co.owner_id,co.seller_name,co.phone,co.next_trace_time,co.sign_reserve_time,co.sign_service_method,co.owner_type,
                 co.sign_reserve_area,co.sign_reserve_city,sign_reserve_province,sign_reserve_address,co.sign_reserve_store,co.contact_person,
                 con.id as consult_id,con.emp_id,con.dealer_id,con.consult_remark,con.consult_status,con.updatetime,con.createtime,
                 pl.fid,pl.bank_account";
        $prefix = C('DB_PREFIX');
        $res = $this->Consult->alias('con')->field($cols)
            ->join($prefix . "order as o ON o.order_id = con.order_id")
            ->join($prefix . "cars as c ON c.car_id = con.car_id")
            ->join($prefix . "car_owner as co ON co.owner_id = con.owner_id")
            ->join("LEFT JOIN " . $prefix . "pay_log as pl ON pl.car_id = con.car_id AND pl.pay_type = 1")
            ->where($condition)->find();
//        echo M()->_sql();
        $brand = $this->CarModel->get_model_by_id($res['brand_id'], 'brand');
        $series = $this->CarModel->get_model_by_id($res['series_id'], 'series');
        $model = $this->CarModel->get_model_by_id($res['model_id']);
        $res['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        $res['car_color'] = C('CAR_COLOR.' . $res['car_color']);
        $res['emission'] = C('INT_EMISSION_STD.' . $res['emission']);
        $res['plate_prefix'] = C('PLATE_PREFIX.' . $res['plate_prefix']);
        $res['pointer_mileage'] = formatMileage($res['pointer_mileage']);
        $res['location_area_name'] = $this->Addr->get_name_by_code($res['location_area']);
        $res['reg_city'] = $this->Addr->get_name_by_code($res['reg_city']);
        $res['car_plate_number'] = C('PLATE_PREFIX')[$res['plate_prefix']] . $res['plate_suffix'];
        //出价排名
        $order = new \AuctionCore\AuctionOrder\AuOrder($res['order_id']);
        $rank_data = $order->get_order_biding_rank($res['order_id']);

        $res['rank_data'] = array_slice($rank_data, 0, 3);
        $reserve_price_format = format_money($res['reserve_price']);
        $res['reserve_price_count'] = $res['reserve_price'];
        $res['reserve_price'] = $reserve_price_format;
        //预约信息
        $res['service_method'] = C('SERVICE_METHOD')[$res['sign_service_method']];
        if ($res['sign_service_method'] == 3) {
            $store = new \AuctionCore\Other\Store();
            $map['store_id'] = ['eq', $res['sign_reserve_store']];
            $store_detail = $store->detail($map);
            $res['reserve_store'] = $store_detail['store_name'];
        } elseif ($res['sign_service_method'] == 2) {
            $addr = new \AuctionCore\Other\Address();
            $province = $addr->get_name_by_code($res['sign_reserve_province']);
            $city = $addr->get_name_by_code($res['sign_reserve_city']);
            $area = $addr->get_name_by_code($res['sign_reserve_area']);
            $res['reserve_address'] = $province . " " . $city . " " . $area . " " . $res['sign_reserve_address'];
        }
        $owner = new \AuctionCore\CarOwner\Owner($res['owner_id']);
        $remark = $owner->read_remark(['order_id' => $res['order_id'], 'result' => 4]);
        $res['remark'] = $remark['remark'];
        $bidding_best_price = $res['bidding_best_price'] > $res['bid_best_price'] ? $res['bidding_best_price'] : $res['bid_best_price'];
        $res['bidding_best_price'] = format_money($bidding_best_price);
        $res['bidding_best_price_count'] = sprintf('%.2f', ($bidding_best_price - $res['consult_increase']));
        $res['suggest_price'] = $res['suggest_min_price'] . '元' . '-' . $res['suggest_max_price'] . '元';
        $res['owner_success_price'] = $res['success_price'] + $res['company_subsidies'];
        $res['dealer_success_price'] = $res['success_price'] + $res['commision'] + $res['transfer_fee'];
        $res['sign_reserve_time'] = transform_date($res['sign_reserve_time']);

        if($res['car_source'] == 1 && !empty($res['bank_account'])){
            $bank_account = json_decode($res['bank_account'],true);
            $res['bank_name'] = $bank_account['bank_name'];
            $res['card_no'] = $bank_account['card_no'];
            $res['account_name'] = $bank_account['account_name'];
        }
        $res['owner_type_name'] = C('OWNER_TYPE_NAME')[$res['owner_type']];
        return $res;
    }

    /**
     * 更新consult表
     *
     * @param array $data
     *
     * @return bool|mixed
     */
    public function update_consult($data = array())
    {
        if (empty($data)) {
            return false;
        }
        return $this->Consult->save($data);
    }

    /**
     * 创建双方磋商跟踪日志
     *
     * @param array $data
     *
     * @return bool
     */
    public function add_consult_trace_log($data = array())
    {
        if (empty($data)) {
            return false;
        }
        $data['createtime'] = date("Y-m-d H:i:s");
        return $this->ConsultTraceLog->add($data);
    }

    /**
     * 获取拍单的磋商信息
     *
     * @param $order_id
     * @param  $map
     */
    public function get_consult_detail($order_id, $map = [])
    {
        if ($order_id < 1) {
            return false;
        }
        $map['order_id'] = ['eq', $order_id];
        return $this->Consult->where($map)->find();
    }

    /**
     * 获取双方磋商跟踪日志
     *
     * @param $order_id
     * @return array
     */
    public function get_consult_trace_log($order_id)
    {
        if (empty($order_id)) {
            return false;
        }
        $condition['order_id'] = ['eq', $order_id];
        $order = 'id DESC';
        $list = $this->ConsultTraceLog->where($condition)->order($order)->select();
        if (!empty($list)) {
            foreach ($list as $key => $val) {
                $employee = \AuctionCore\Account\Back\Employee::user_info_id($val['emp_id']);
                $list[$key]['emp_name'] = $employee['real_name'];
            }
        }
        return $list;
    }


}
